# _*_ coding:utf-8 _*_
# @Time : 2021/8/30 17:07

# @Author : feifei

# @File : findphone.py

# @Software: PyCharm

import csv
from configparser import ConfigParser
import sys
import time
from phone import Phone
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog
from PyQt5 import QtCore
from PyQt5.QtGui import QIcon
from findphone_ui import Ui_findphone
from SecondWindow import Ui_queren_Dialog


class FindMainWindow(QMainWindow, Ui_findphone):

    def __init__(self):
        super(FindMainWindow, self).__init__()
        _translate = QtCore.QCoreApplication.translate
        self.setupUi(self)
        self.config_dict = self.get_config()
        self.setWindowTitle("归属地查询工具_%s" % self.config_dict['version'])
        self.setWindowIcon(QIcon(self.config_dict['ico_name']))
        beizhu_str = "    %s   %s" % (self.config_dict['copyright'], self.config_dict['update_time'])
        self.beizhu.setText(_translate("findphone", beizhu_str))
        # 触发单条查询
        self.one_cx_submit.clicked.connect(self.single_cx)
        # 打开文件
        self.more_cx_file.clicked.connect(self.open_file)
        self.more_cx_submit.clicked.connect(self.many_cx)
        self.add_Button.clicked.connect(self._add_first)
        self.delete_Button.clicked.connect(self._delete_first)
        self.xg_Button.clicked.connect(self.xg_first)
        self.ex_summit.clicked.connect(self.ex_data)
        self.province_combo.currentIndexChanged.connect(self.add_city_items)
        self.xg_province_combo.currentIndexChanged.connect(self.add_city_items)
        self.ex_province.currentIndexChanged.connect(self.add_city_items)
        self.checkSecond = CheckSecondWindow()

        self.open_file_name = []
        p = Phone()
        self.city_dict = p.city_dict
        for p in self.city_dict:
            self.province_combo.addItem(p)
            self.xg_province_combo.addItem(p)
            self.ex_province.addItem(p)

    def get_config(self):
        config = ConfigParser()
        config.read('.etc/common.ini', encoding='utf-8')
        c_dict = {}
        for op in config.options('config'):
            c_dict[op] = config.get('config', op)
        return c_dict

    # 单个查询入口
    def single_cx(self):
        phone_num = self.one_num_text.text()
        c1, c2 = self.check_input(phone_num)
        if c1 == 0:
            self.show_result_text.append(self.red_font(c2))
        elif c1 == 1:
            single_p = Phone()
            r_dict = single_p.find(c2)
            if r_dict is None:
                self.show_result_text.append(self.red_font("该号段不存在，查询失败"))
            else:
                self.show_result_text.append("号段：%s,省份：%s,城市：%s,运营商：%s" % (r_dict['phone'], r_dict['province'],
                                                                           r_dict['city'], r_dict['phone_type']))

    # 批量查询入口
    def many_cx(self):
        if len(self.open_file_name) == 0 or self.open_file_name[0] == '':
            self.show_result_text.append(self.red_font("尚未选择文件"))
        else:

            self.show_result_text.append("开始读取")
            many_p = Phone()
            try:
                r_file = open('result.csv', 'w', encoding='utf-8_sig')
                csvwriter = csv.writer(r_file, dialect=("excel"), lineterminator='\n')
                csvwriter.writerow(['号码', '归属省份', '归属城市', '运营商'])
                count = 0
                with open(self.open_file_name[0], 'r', encoding='utf-8') as f:
                    for line in f.readlines():
                        count += 1
                        c1, c2 = self.check_input(line.strip('\n'))
                        if c1 == 0:
                            outputline = [line.strip('\n') + '\t', c2]
                        elif c1 == 1:
                            r = many_p.find(c2)
                            if r is None:
                                outputline = [line.strip('\n') + '\t', '号段不存在']
                            else:
                                outputline = [r['phone'] + '\t', r['province'], r['city'], r['phone_type']]
                        csvwriter.writerow(outputline)
                        if count % 1000 == 0:
                            self.show_result_text.append("已读取%d" % count)
                r_file.close()
                self.show_result_text.append("已读取%d" % count)
                self.show_result_text.append("读取完毕，结果见result.csv")
                self.more_cx_file_name.setText("")
                self.open_file_name = []
            except:
                self.show_result_text.append(self.red_font("result.csv已打开，请关闭后再执行"))

    # 查找函数
    # 选择文件函数
    def open_file(self):
        self.open_file_name = QFileDialog.getOpenFileName(self, '选择文件', '.', "Text files(*.txt)")
        self.more_cx_file_name.setText(self.open_file_name[0])

    def _add_first(self):
        phone_num = self.add_num_text.text()
        province = self.province_combo.currentText()
        city = self.city_combo.currentText()
        yys = self.yys_combo.currentText()
        if province == '选择省份':
            self.show_result_text.append(self.red_font("请选择省份"))
        else:
            c1, c2 = self.check_input(phone_num)
            if c1 == 0:
                self.show_result_text.append(self.red_font(c2))
            elif c1 == 1:
                show_list = ['您将添加如下信息：', self.red_font('请勿输入完整号码，请只输入号段，点击确定继续添加'), "号段", "省份", "城市", "运营商", phone_num,
                             province, city, yys, '']
                self.checkSecond.Open(show_list)
                self.checkSecond.signal.connect(self._add_second)

    def _add_second(self, params):
        # self.show_result_text.append(params)
        if params == 'y':
            add_p1 = Phone()
            phone_num = self.add_num_text.text()
            province = self.province_combo.currentText()
            city = self.city_combo.currentText()
            yys = self.yys_combo.currentText()
            if add_p1.find(phone_num) is None:
                result_str = add_p1.add_phone(phone_num, province, city, self.get_phone_no_type(yys))
                self.show_result_text.append("添加完成，原始数据文件已备份为%s" % result_str)
            else:
                self.show_result_text.append(self.red_font("号段已存在"))
                r_dict = add_p1.find(phone_num)
                self.show_result_text.append("号段：%s,省份：%s,城市：%s,运营商：%s" % (r_dict['phone'], r_dict['province'],
                                                                           r_dict['city'], r_dict['phone_type']))
            self.checkSecond.signal.disconnect(self._add_second)
        elif params == 'n':
            self.show_result_text.append(self.red_font("已取消添加"))
            self.checkSecond.signal.disconnect(self._add_second)

    def _delete_first(self):
        phone_num = self.delete_num_text.text()
        c1, c2 = self.check_input(phone_num)
        if c1 == 0:
            self.show_result_text.append(self.red_font(c2))
        elif c1 == 1:
            delete_p = Phone()
            r_dict = delete_p.find(c2)
            if r_dict is None:
                self.show_result_text.append(self.red_font("号段不存在，无法删除"))
            else:
                # old_phone, old_province, old_city, old_yys = r_dict['phone'], r_dict['province'],
                # r_dict['city'], r_dict['phone_type']
                list = ['您将删除如下信息：', '是否确认删除', phone_num, r_dict['province'],
                        r_dict['city'], r_dict['phone_type'], "", "", "", "", ""]
                self.checkSecond.Open(list)
                self.checkSecond.signal.connect(self._delete_second)
        # check.show()

    def _delete_second(self, params):
        if params == 'y':
            delete_p1 = Phone()
            result_str = delete_p1.delete_phone(int(self.delete_num_text.text()))
            self.show_result_text.append("删除完成，原始数据文件已备份为%s" % result_str)
            self.checkSecond.signal.disconnect(self._delete_second)
        elif params == 'n':
            self.show_result_text.append(self.red_font("已取消删除"))
            self.checkSecond.signal.disconnect(self._delete_second)

    def xg_first(self):
        phone_num = self.xg_num_text.text()
        province = self.xg_province_combo.currentText()
        city = self.xg_city_combo.currentText()
        yys = self.xg_yys_combo.currentText()
        if province == '选择省份':
            self.show_result_text.append(self.red_font("请选择省份"))
        else:
            c1, c2 = self.check_input(phone_num)
            if c1 == 0:
                self.show_result_text.append(self.red_font(c2))
            elif c1 == 1:
                xg_p = Phone()
                if xg_p.find(c2) is None:
                    self.show_result_text.append(self.red_font("号码不存在，无法修改"))
                else:
                    r_dict = xg_p.find(c2)
                    list = ['您将修改如下信息：', '是否确认修改', phone_num, r_dict['province'],
                            r_dict['city'], r_dict['phone_type'], phone_num, province, city, yys,
                            "修改为"]
                    self.checkSecond.Open(list)
                    self.checkSecond.signal.connect(self._xg_second)

    def _xg_second(self, params):
        if params == 'y':
            phone_num = int(self.xg_num_text.text())
            province = self.xg_province_combo.currentText()
            city = self.xg_city_combo.currentText()
            yys = self.xg_yys_combo.currentText()
            xg_p1 = Phone()
            result_str = xg_p1.alter_phone(phone_num, province, city, self.get_phone_no_type(yys))
            self.show_result_text.append("修改完成，原始数据文件已备份为%s" % result_str)
            self.checkSecond.signal.disconnect(self._xg_second)
        elif params == 'n':
            self.show_result_text.append(self.red_font("已取消修改"))
            self.checkSecond.signal.disconnect(self._xg_second)

    def ex_data(self):
        province = self.ex_province.currentText()
        city = self.ex_city.currentText()
        t = self.ex_yys.currentText()
        time1 = time.time()
        self.show_result_text.append("正在导出，请耐心等待")
        ex_p = Phone()

        phone_dict = ex_p.read_phone(province, city, self.get_phone_no_type(t))
        # self.show_result_text.append(time1)
        file_name = "号段数据_%s_%s_%s.csv" % (province, city, t)
        # # try:
        d_file = open(file_name, 'w', encoding='utf-8_sig')
        csvwriter = csv.writer(d_file, dialect=("excel"), lineterminator='\n')
        csvwriter.writerow(['号段', '归属省份', '归属城市', '运营商'])
        for p_num in phone_dict:
            outline = [phone_dict[p_num]['phone'], phone_dict[p_num]['province'], phone_dict[p_num]['city'],
                       phone_dict[p_num]['phone_type']]
            csvwriter.writerow(outline)
        d_file.close()
        time2 = time.time()
        dur_time = time2 - time1
        self.show_result_text.append("文件已导出至  %s,耗时%.2f秒" % (file_name, dur_time))
        # # except:
        # #     self.show_result_text.append(self.red_font("%s已打开，请关闭后再执行" % file_name))

    def get_phone_no_type(self, phone_type):
        if phone_type == "不限":
            return phone_type
        if phone_type == "联通虚拟运营商":
            return 7
        if phone_type == "移动虚拟运营商":
            return 6
        if phone_type == "电信虚拟运营商":
            return 5
        if phone_type == "虚拟运营商":
            return 4
        if phone_type == "电信":
            return 3
        if phone_type == "联通":
            return 2
        if phone_type == "移动":
            return 1

    def check_input(self, phone_num):
        if phone_num.isnumeric():
            str_phone_num = str(phone_num)
            int_phone_num = int(phone_num)
            if len(str_phone_num) < 7:
                return [0, "号段小于7位，请检查后重新输入"]
            elif len(str_phone_num) > 16:
                return [0, "号段过长，请检查后重新输入"]
            else:
                return [1, int_phone_num]
        else:
            return [0, "包含非数字,请重新输入"]

    def add_city_items(self):
        sheng = self.province_combo.currentText()
        if sheng is not None:
            if sheng != '选择省份':
                self.city_combo.clear()
                for c in self.city_dict[sheng]:
                    self.city_combo.addItem(c)
            else:
                self.city_combo.clear()
                self.city_combo.addItem('选择城市')

        xg_sheng = self.xg_province_combo.currentText()
        if xg_sheng is not None:
            if xg_sheng != '选择省份':
                self.xg_city_combo.clear()
                for c1 in self.city_dict[xg_sheng]:
                    # self.show_result_text.append(c1)
                    self.xg_city_combo.addItem(c1)
            else:
                self.xg_city_combo.clear()
                self.xg_city_combo.addItem('选择城市')
        ex_sheng = self.ex_province.currentText()
        if ex_sheng is not None:
            if ex_sheng != '不限':
                self.ex_city.clear()
                self.ex_city.addItem('不限')
                for c1 in self.city_dict[ex_sheng]:
                    self.ex_city.addItem(c1)
            else:
                self.ex_city.clear()
                self.ex_city.addItem('不限')

    def red_font(self, string):
        return '<font color=\"#FF0000\">' + string + '</font>'


class CheckSecondWindow(QMainWindow, Ui_queren_Dialog):
    signal = QtCore.pyqtSignal(str)

    def __init__(self):
        super(CheckSecondWindow, self).__init__()
        self.setupUi(self)
        self.setWindowTitle("归属地查询工具_V3.2")
        self.setWindowIcon(QIcon('SRC/police_favicon.ico'))
        self.ok_button.clicked.connect(self.ok_return)
        self.no_button.clicked.connect(self.no_return)

    def ok_return(self):
        self.signal.emit('y')
        self.close()

    def no_return(self):
        self.signal.emit('n')
        self.close()

    def Open(self, phone_list):
        _translate = QtCore.QCoreApplication.translate
        self.show_label_1.setText(_translate("queren_Dialog", phone_list[0]))
        self.show_label_3.setText(_translate("queren_Dialog", phone_list[1]))
        self.label_1.setText(_translate("queren_Dialog", phone_list[2]))
        self.label_2.setText(_translate("queren_Dialog", phone_list[3]))
        self.label_3.setText(_translate("queren_Dialog", phone_list[4]))
        self.label_4.setText(_translate("queren_Dialog", phone_list[5]))
        self.label_5.setText(_translate("queren_Dialog", phone_list[6]))
        self.label_6.setText(_translate("queren_Dialog", phone_list[7]))
        self.label_7.setText(_translate("queren_Dialog", phone_list[8]))
        self.label_8.setText(_translate("queren_Dialog", phone_list[9]))
        self.label_9.setText(_translate("queren_Dialog", phone_list[10]))
        self.show()


if __name__ == '__main__':
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
    app = QApplication(sys.argv)
    find_mainwindow = FindMainWindow()
    find_mainwindow.show()
    # a = CheckSecondWindow()
    # a.Open('q','w','e')
    sys.exit(app.exec_())
